package com.wisnews.controller.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wisnews.pojo.Result;
import com.wisnews.pojo.sec.entity.Operator;
import com.wisnews.pojo.sr.vo.EmailAuthCodeMatchingVO;
import com.wisnews.service.Impl.QQEmailService;
import com.wisnews.service.sec.Impl.OperatorServiceImpl;
import com.wisnews.util.AuthCodeUtil;
import com.wisnews.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description：邮件相关处理类
 * @Author: yuyd
 * @Email: yyd8358@foxmail.com
 * @Date: 2020/12/24 14:45
 * @Version 1.0
 */
@RestController
@Slf4j
public class SendEmailController {

    @Autowired
    @Qualifier("sendEmail")
    private QQEmailService qqEmailService;

    @Autowired
    private OperatorServiceImpl operatorService;

    @Autowired
    private RedisTemplate redisTemplate;



    @RequestMapping(value = "resetPasswordByEmail/{email}",method = RequestMethod.POST)
    public Result resetPasswordByEmail(@PathVariable("email") String email){

        //1.邮箱格式校验

        //2.通过邮箱查询用户
        LambdaQueryWrapper<Operator> queryWrapper = Wrappers.lambdaQuery();
        Operator operator = operatorService.getOne(queryWrapper.eq(Operator::getEmail, email));
        //3.初始化为默认密码
        if (!Objects.isNull(operator)) {
            operator.setPassword(operator.getRecentPassword());
            try {
                //发送重置密码邮件
                qqEmailService.sendSimpleMail(email, "密码重置", "您的密码已经重置为初始密码" + operator.getRecentPassword());
                operatorService.updateById(operator);
            }catch (MailException mailException){
                log.error(mailException.toString());
                return new Result(Constants.SYS_CODE.SUCCESS,"重置密码失败，请重试！");
            }
        }else {
            return new Result(Constants.SYS_CODE.SUCCESS,"您的邮箱没有绑定登录账号！");
        }
        return new Result(Constants.SYS_CODE.SUCCESS,"重置密码邮件发送成功！");
    }



    ////发送简单邮件
    //通过邮箱发送验证码
    //这里前台不返回邮箱验证码，保证安全，使用邮箱作为key,验证码作为value 存入redis
    @RequestMapping(value = "sendAuthCode/{email}",method = RequestMethod.POST)
    public Result sendAuthCodeByEmail(@PathVariable("email") String email){

        if (StringUtils.isBlank(email)){
            return new Result(Constants.SYS_CODE.FAIL, Constants.SYS_CODE.SUCCESS_MESSAGE);
        }

        String authCode = AuthCodeUtil.genRodomCode();

        String auth = (String)redisTemplate.opsForValue().get(email);
        //缓存中 不存在验证码
        if (StringUtils.isBlank(auth)){
            try {
                qqEmailService.sendSimpleMail(email,"智慧新闻验证码","您正在智慧新闻验证邮箱，您的验证码为 "+ authCode+" 三分钟后超时！请勿将验证码告诉他人！");
               // redisTemplate.opsForValue().set(email,authCode,3, TimeUnit.MINUTES);
            }catch (MailException mailException){
                log.error("验证码发送失败"+mailException);
                return new Result(Constants.SYS_CODE.FAIL,"验证码发送失败！");
            }

        }else {  //验证码重复发送
            return new Result(Constants.SYS_CODE.FAIL,"重复发送，三分钟后重试！");
        }

        //验证码存入redis 3分钟后超时
        redisTemplate.opsForValue().set(email,authCode,3, TimeUnit.MINUTES);

        return new Result(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE);
    }


    @RequestMapping(value = "sendHtmlEmail/{email}",method = RequestMethod.GET)
    public Result sendHtmlEmail(@PathVariable(value = "email",required = true) String email){

        if (StringUtils.isBlank(email)){
            return new Result(Constants.SYS_CODE.FAIL, Constants.SYS_CODE.SUCCESS_MESSAGE);
        }

        String content="<html>\n"+"<body>\n"
                + "<h3>hello world!测试发送html格式邮件</h3>\n"
                +"</body>\n"+"</html>";

        qqEmailService.sendSimpleMail(email,"张梦蝶爱你哦！",content);

        return new Result(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE);
    }


    //邮箱验证码 匹配
    @RequestMapping(value = "authCodeMatching",method = RequestMethod.POST)
    public Result authCodeMatching(@RequestBody EmailAuthCodeMatchingVO emailAuthCodeMatchingVO){


        String email = emailAuthCodeMatchingVO.getUserEmail();

        String authCode = emailAuthCodeMatchingVO.getAuthCode();

        if (StringUtils.isBlank(email) || StringUtils.isBlank(authCode)){
            return new Result(Constants.SYS_CODE.FAIL, Constants.SYS_CODE.FAIL_MESSAGE);
        }

        String code = (String)redisTemplate.opsForValue().get(email);

        log.error(email+"验证码："+code);

        //匹配成功
        if (StringUtils.isNotBlank(code) && code.equals(authCode)){
            return  new Result(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE);
        }

        return new Result(Constants.SYS_CODE.FAIL, Constants.SYS_CODE.FAIL_MESSAGE);
    }

}
